//
//  AppDelegate.m
//  kankanVideo
//
//  Created by wangbo on 5/21/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//



#import "AppDelegate.h"

#import "GuiderViewController.h"
#import "ViewController.h"
#import "ConfigData.h"
#import <CoreData/CoreData.h>
#import "GANTracker.h"

// Dispatch period in seconds
static const NSInteger kGANDispatchPeriodSec = 10;
// **************************************************************************
// PLEASE REPLACE WITH YOUR ACCOUNT DETAILS.
// **************************************************************************
static NSString* const kAnalyticsAccountId = @"UA-21873800-1";

@implementation AppDelegate
//@synthesize token;

//@synthesize zyViewController;
@synthesize window = _window;
//@synthesize viewController = _viewController;
@synthesize navigationController=_navigationController;
@synthesize managedObjectModel,managedObjectContext,persistentStoreCoordinator;
@synthesize alertView;

-(void)saveContext{
    NSError *error = nil;   
    NSManagedObjectContext *objectContext = self.managedObjectContext;   
    if (objectContext != nil)   
    {
        if ([objectContext hasChanges] && ![objectContext save:&error])     
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);       
            abort();     
        }   
    }
}

-(void)showAlert:(NSString *)theTitle{
    if(!alertView)alertView=[[MyAlertView alloc]initWithFrame:CGRectMake(self.window.frame.size.width/2-140/2, self.window.frame.size.height/2-100/2, 140, 100)];
    if(alertView.superview!=self.window){
        [alertView setTitle:theTitle];
        [self.window addSubview:alertView];
    }else{
        [alertView setTitle:theTitle];
    }
    NSLog(@"myalertview_show:%d",alertView.retainCount);
    NSLog(@"alert_content:%@",theTitle);
}
-(void)hideAlert{
    if(alertView.superview==self.window){
        [alertView removeFromSuperview];
    }
    NSLog(@"myalertview_hide:%d",alertView.retainCount);
}
-(NSString*)applicationDocumentsDirectory{
    //return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
    //return [NSURL URLWithString:basePath];
}
- (void)dealloc
{
    [_window release];
    //[_viewController release];
    [_navigationController release];
    [managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    [super dealloc];
}

-(void)swipeHandler:(UISwipeGestureRecognizer*)recognizer{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[GANTracker sharedTracker]startTrackerWithAccountID:kAnalyticsAccountId dispatchPeriod:kGANDispatchPeriodSec delegate:nil];
    NSError *error;
    if (![[GANTracker sharedTracker] setCustomVariableAtIndex:1
                                                         name:@"iOS"
                                                        value:@"iOS"
                                                    withError:&error]) {
        NSLog(@"error in setCustomVariableAtIndex");
    }
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    //self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    
    
    /*UISwipeGestureRecognizer *recegnizer=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeHandler:)];
    [recegnizer setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.window addGestureRecognizer:recegnizer];
    [recegnizer release];*/
    
    /*NSArray* _arr=[[MyCoreData shareInstance]queryConfig];
    if (_arr.count==0) {
        self.token=[NSString stringWithString:@""];
    }else{
        ConfigData *_data=(ConfigData*)[_arr objectAtIndex:0];
        if ([_data.token isEqualToString:@""]) {
            self.token=[NSString stringWithString:@""];
        }else{
            self.token=_data.token;
        }
    }*/
    
    GuiderViewController *guider=[[GuiderViewController alloc]init];
    //ViewController *guider=[[[ViewController alloc]initWithNibName:@"ViewController" bundle:nil]autorelease];
    self.navigationController=[[UINavigationController alloc]initWithRootViewController:guider];
    [self.navigationController setNavigationBarHidden:YES];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
    NSError *error;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSAssert(0, @"save changes failed when terminage application!");
        }
    }
}

- (NSManagedObjectContext *)managedObjectContext
{
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    //从本地所有 xcdatamodel 文件中获得这个 CoreData 的数据模板
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
    return managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
    //数据库名为TestDB.sqlite
    NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"mysql4.sqlite"]];
    NSError *error;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        NSAssert(0, @"persistentStoreCoordinator init failed and %@!",error);
    }
    return persistentStoreCoordinator;
}

@end
